<?php
// +----------------------------------------------------------------------
//            -------------------------
//           /   / ----------------\  \
//          /   /             \  \
//         /   /              /  /
//        /   /    /-------------- /  /
//       /   /    /-------------------\  \
//      /   /                   \  \
//     /   /                     \  \
//    /   /                      /  /
//   /   /      /----------------------- /  /
//  /-----/      /---------------------------/
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://baimifan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Sage 2016/4/19  14:05
// +----------------------------------------------------------------------

namespace Common\Model;
use Think\Model;

/*
 * 订单模型
 * 主要针对订单的新增等操作
 * */
class OrderModel extends Model
{
    protected $tableName="Pay";
    /*
     * 通用
     * 生成新的pay条目
     * 支付方式，
     * 返回新生成的pay_id
     *type:
     *      借书：1；购书：2；充值：3；活动：4；
     *  */
    function bear_new_pay($pay_way="wechat",$type,$money=0,$summary="未知"){
        $Pay=M("Pay");
        $data["status"]=0;
        $data["way"]=$pay_way;
        $data["money"]=round($money,2);
        $data["type"]=$type;
        $data["summary"]=$summary;
        $data["user_id"]=session("user_id");
        $pay_id=$Pay->data($data)->add();
        if($data["money"]==0){
            return $pay_id;
        }else{
            return $pay_id;
        }

    }
    /*
     * 插入新的 活动订单
     * 活动id，用户id，支付方式
     * 返回生成的pay_id，用于传递给支付中心
     * */
    function bear_order_activity($user_id,$activity_id,$pay_way="wechat"){
        //先查询是否已提交订单，提交过则获取pay_id直接前往支付

        $Apply=M("Activity_apply");
        $countapp=$Apply->where("user_id=$user_id AND activity_id=$activity_id")->count();

        if($countapp>0){
            $dapply=$Apply->where("user_id=$user_id AND activity_id=$activity_id")->field("pay_id")->find();
            $pay = M('pay');
            $money = $pay->where(['pay_id'=>$dapply['pay_id']])->getField('money');
            $res['pay_id'] = $dapply['pay_id'];
            if($money==0){
                $res['state'] = 300;
            }else{
                $res['state'] = 200;
            }
            return $res;
        }
        $Activity=M("Activity");
        $d=$Activity->where("activity_id=$activity_id")->field("price_apply,price_material")->find();
        $money_apply=$d["price_apply"];  //报名费
        $money_material=$d["price_material"];  //材料费

        $summary="微信线上活动报名,";
        //活动费用的计算
        $User=D("User");
        $frees=$User->getFreenum_apply(); //可免报名费次数

        if($frees>0){
            $is_applyfree=1; //免报名费
            $money_apply=0; //免活动费
            $summary.="免报名费,";
            $discount=1;
        }else{
            $is_applyfree=0;
            $discount=$User->getDiscount_apply();
            $summary.="报名费原价:".$money_apply."元,";
            $summary.="折扣为:".$discount.",";
            $money_apply=$money_apply*$discount; //活动折扣价
            $summary.="打折后:".$money_apply."元,";
        }
        $summary.="材料费:".$money_material."元,";
        $money=$money_apply+$money_material;    //总费用（打折后的实际总金额）=打折后活动费+材料费

        $summary.="折后总计:".$money."元";
        $pay_id=$this->bear_new_pay($pay_way,"4",$money,$summary);

        $data["activity_id"]=$activity_id;
        $data["user_id"]=$user_id;
        $data["pay_id"]=$pay_id;
        $data["is_applyfree"]=$is_applyfree;
        $data["discount_apply"]=$discount;
        $data["contactor"]=$User->getContactor();
        $apply_id=$Apply->data($data)->add();
        if($apply_id){
            $res['pay_id'] = $pay_id;
            if($money==0){
                $res['state'] = 300;
            }else{
                $res['state'] = 200;
            }
            return $res;
        }
    }
    /*
     * 插入新的借书买书订单
     * 用户id，类型type（1:借书;0:买书），地址（json），是否免运费(1:免费;0:不免运费)，图书列表数组
     * */
    function bear_order_book_rent($user_id,$type=1,$address,$is_ffree,$blist,$remark,$pay_way="wechat"){
        $summary="微信线上借书,";
        //计算运费
        if($is_ffree){
            $money_freight=0;
            $summary.="免运费,";
        }else{
            //不免运费
            //根据地址获取当前地区的价格
            $deaddress=get_object_vars(json_decode($address));
            $DAdr=D("Address");
            $money_freight=$DAdr->getFreightRent($deaddress['province'],$deaddress['city'],$deaddress['district']);
            $summary.="邮寄地区:".$deaddress['province'].','.$deaddress['city'].','.$deaddress['district'].',运费:'.$money_freight."元,";
        }
        //计算购书费
        $money_book=0;
        if($type==1){
            $money_book=0;
            $summary.="购书费:0元,";
        }else{
            //当前图书列表数组去获取书价格
            $Book=M("Book");
            $summary.="购书费:";
            foreach($blist as $k=>$v){
                //echo $v['book_id'].$v['num'];
                $map["book_id"]=$v['book_id'];
                $dbook=$Book->where($map)->field("dj")->find();
                $money_book+=$dbook['dj']*$v['num'];
                $summary.=$dbook['dj']."*".$v['num']."元;";
            }
        }

        $money=$money_book+$money_freight;
        $summary.="共:".$money_book."元,"."总价:".$money."元";
        //生成订单
        $pay_id=$this->bear_new_pay($pay_way,"1",$money,$summary);

        $bdata["user_id"]=$user_id;
        $bdata["money"]=$money_book;
        $bdata["price_freight"]=$money_freight;
        $bdata["type"]=$type;
        $bdata["address"]=$address;
        $bdata["pay_id"]=$pay_id;
        $bdata["is_freightfree"]=$is_ffree;
        $bdata["is_online"]='0';
        $bdata["order_remark"]=$remark;
        $Order=M("Order_book");
        $order_id=$Order->data($bdata)->add();
        if($order_id){
            $Cart=M("Cart");
            foreach($blist as $k=>$v){
                //批量形成订单图书数组
                $odatalist[] = array('order_id'=>$order_id,'book_id'=>$v['book_id'],'quantity'=>$v['num'],'type'=>$type);

                //更新书包或购物车中的图书
                $cmap['user_id']=$user_id;
                $cmap['book_id']=$v['book_id'];
                $cmap['type']=$type;
                $d=$Cart->where($cmap)->find();
                if($d){
                    if($d['quantity']<$v['num']){
                        $dec=$d['quantity'];
                    }else{
                        $dec=$v['num'];
                    }
                    $r=$Cart->where($cmap)->setDec('quantity',$dec);
                }
            }
            $Cart->where("quantity<1")->delete();

            $Order_book=M("Order_has_book");
            $r=$Order_book->addAll($odatalist);
            return $pay_id;
        }
    }
    //生成购书订单
    function bear_order_book_buy($user_id,$type=0,$address,$blist,$remark,$pay_way="wechat"){
        if($user_id==""){
            $user_id=session("user_id");
        }
        $summary="微信线上购书,";
        //计算运费
        //不免运费
        //根据地址获取当前地区的价格
        $deaddress=get_object_vars(json_decode($address));
        $DAdr=D("Address");
        $money_freight=$DAdr->getFreightBuy($deaddress['province'],$deaddress['city'],$deaddress['district']);

        $summary.="邮寄地区:".$deaddress['province'].','.$deaddress['city'].','.$deaddress['district'].',运费:'.$money_freight."元,";

        //计算购书费
        $money_book=0;

        //当前图书列表数组去获取书价格
        $Book=M("Book");
        $summary.="购书费(原价):";
        foreach($blist as $k=>$v){
            //echo $v['book_id'].$v['num'];
            $map["book_id"]=$v['book_id'];
            $dbook=$Book->where($map)->field("dj")->find();
            $money_book+=$dbook['dj']*$v['num'];
            $summary.=$v['num']."件".$dbook['dj']."元;";
        }

        $Card=M("Card");
        $dc=$Card->where("user_id=$user_id")->find();
        if(strtotime($dc['expire_time'])<time()){
            $discount_buy=1;
        }else{
            $discount_buy=$dc["discount_buy"];
        }
        $summary.="会员折扣为:".$discount_buy.",";

        $money=$money_book*$discount_buy+$money_freight;
        $summary.="打折后共:".$money_book*$discount_buy."元,"."总价:".$money."元";
        //生成订单
        $pay_id=$this->bear_new_pay($pay_way,"2",$money,$summary);
        $bdata["user_id"]=$user_id;
        $bdata["money"]=$money_book;
        $bdata["price_freight"]=$money_freight;
        $bdata["type"]=$type;
        $bdata["address"]=$address;
        $bdata["pay_id"]=$pay_id;
        $bdata["discount_buy"]=$discount_buy;
        $bdata["is_online"]='0';
        $bdata["order_remark"]=$remark;
        $Order=M("Order_book");
        $order_id=$Order->data($bdata)->add();
        if($order_id){
            $Cart=M("Cart");
            foreach($blist as $k=>$v){
                //批量形成订单图书数组
                $odatalist[] = array('order_id'=>$order_id,'book_id'=>$v['book_id'],'quantity'=>$v['num'],'type'=>$type);
                //更新书包或购物车中的图书
                $cmap['user_id']=$user_id;
                $cmap['book_id']=$v['book_id'];
                $cmap['type']=$type;
                $d=$Cart->where($cmap)->find();
                if($d){
                    if($d['quantity']<$v['num']){
                        $dec=$d['quantity'];
                    }else{
                        $dec=$v['num'];
                    }
                    $r=$Cart->where($cmap)->setDec('quantity',$dec);
                }
            }
            $Cart->where("quantity<1")->delete();

            $Order_book=M("Order_has_book");
            $Order_book->addAll($odatalist);
            return $pay_id;
        }
    }
    //插入新的充值订单
    function bear_order_vip($user_id,$type_id,$pay_way="wechat"){
        if($user_id==""){
            $user_id=session("user_id");
        }
        $Card=M("Card");
        $countc=$Card->where("user_id=$user_id")->count();
        if($countc==0){
            $datac['user_id']=$user_id;
            $card_id=$Card->data($datac)->add();
        }else{
            $card_id=$Card->where("user_id=$user_id")->find();
            $card_id=$card_id['card_id'];
        }

        $Type=M("Deposit_type");
        $dt=$Type->where("type_id=$type_id")->find();
        $money=$dt['price'];
        $summary="微信线上会员充值,名称:".$dt['name'].",延期时间:".$dt['month']."个月,金额:".$money;
        $pay_id=$this->bear_new_pay($pay_way,"3",$money,$summary);

        $Deposit=M("Deposit");
        $data["card_id"]=$card_id;
        $data["type_id"]=$type_id;
        $data["pay_id"]=$pay_id;
        $deposit_id=$Deposit->data($data)->add();
        if($deposit_id){
            return $pay_id;
        }
    }
    //是否已支付
    //返回1：已支付；0：未支付
    function is_pay($pay_id){
        $Pay=M("Pay");
        $count=$Pay->where("pay_id=$pay_id AND status=1")->count();
        return $count;
    }
    //是否已取消
    //返回1：已取消；0：未取消-可操作订单
    function is_cancel($pay_id){
        $Pay=M("Pay");
        $count=$Pay->where("pay_id=$pay_id AND status=-1")->count();
        return $count;
    }
    //是否存在此订单
    //返回1：存在；0：不存在
    function is_exist($pay_id){
        $Pay=M("Pay");
        $count=$Pay->where("pay_id=$pay_id")->count();
        return $count;
    }
}   